package com.yhsoft.common.utils;

import com.alibaba.fastjson2.JSONObject;
import com.yhsoft.common.exception.BusinessException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestTemplate;

import java.io.IOException;


/**
 * @author: yyyyyyyh
 * @create: 2023-10-14
 * @Version 1.0
 **/
public class AccessTokenUtil {
    private static final Logger logger = LoggerFactory.getLogger(AccessTokenUtil.class);

    private static final String ACCESS_TOKEN_URL = "https://qyapi.weixin.qq.com/cgi-bin/gettoken";
    private static final String getAccessTokenUrl = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=%s&secret=%s";

    // 缓存access_token，避免频繁获取
    private static String accessToken;
    private static long expiredTime;

    /**
     * 获取access_token
     *
     * @param appId     appId
     * @param appSecret appSecret
     * @return access_token
     * @throws IOException
     */
    public static String getAccessToken(String appId, String appSecret){
        //如果缓存中的access_token还没有过期，则直接返回缓存中的access_token
        if (accessToken != null && System.currentTimeMillis() < expiredTime) {
            return accessToken;
        }

        // 向企业微信API请求access_token
        // 获取调用凭证
        String requestUrl = String.format(getAccessTokenUrl, appId, appSecret);
        logger.info("获取调用凭证requestUrl:" + requestUrl);
        RestTemplate restTemplate = new RestTemplate();
        ResponseEntity<String> entity = restTemplate.getForEntity(requestUrl, String.class);
        logger.info("getAccessTokenUrlEntity:" + entity.toString());
        String body = entity.getBody();
        JSONObject result = JSONObject.parseObject(body);
        if (result == null || !result.containsKey("access_token")) {
            throw new BusinessException("调用获取调用凭证接口出错，请稍后重试～");
        }
        expiredTime = System.currentTimeMillis() + (7200 - 60) * 1000;
        accessToken = result.getString("access_token");
        return accessToken;
    }
}
